package com.yunze.iotapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.yunze.apiCommon.upstreamAPI.DianXinCMP.Inquire.Query_DX;
import com.yunze.apiCommon.upstreamAPI.DianXinCMP5G.Inquire.Query_DX5G;
import com.yunze.apiCommon.upstreamAPI.YiDongEC.Inquire.Query_YD;
import com.yunze.apiCommon.utils.Arith;
import com.yunze.apiCommon.utils.VeDate;
import com.yunze.common.mapper.mysql.YzAgentPackageMapper;
import com.yunze.common.mapper.mysql.YzCardMapper;
import com.yunze.common.mapper.mysql.YzCardPacketMapper;
import com.yunze.common.mapper.mysql.YzOrderMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalPrimaryIccidMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalPrimaryMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalPrimaryOrdNoMapper;
import com.yunze.iotapi.service.NewOpenApiService;
import com.yunze.iotapi.utils.ResponseJson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/10/09/15:14
 * @Description:
 */
@Service
public class NewOPenApiServiceImpl implements NewOpenApiService {
    @Resource
    private YzCardMapper yzCardMapper;
    @Resource
    private YzAgentPackageMapper agentPackageMapper;
    @Resource
    private YzCardPacketMapper yzCardPacketMapper;
    @Resource
    private YzApplicationforRenewalPrimaryMapper renewalPrimaryMapper;
    @Resource
    private YzOrderMapper yzOrderMapper;
    @Resource
    private YzApplicationforRenewalMapper yzApplicationforRenewalMapper;
    @Resource
    private YzApplicationforRenewalPrimaryOrdNoMapper yzApplicationforRenewalPrimaryOrdNoMapper;
    @Resource
    private YzApplicationforRenewalPrimaryIccidMapper yzApplicationforRenewalPrimaryIccidMapper;

    @Override
    public Map<String, Object> queryCardInfoList(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dataList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String, Object> cardInfoMaps = yzCardMapper.selectCardInfoList(iccid);
            dataList.add(cardInfoMaps);
        }
        System.err.println(dataList);
        return new ResponseJson().initSuccessOpen(dataList);
    }

    @Override
    public Map<String, Object> queryCardDetail(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dataList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String, Object> cardInfoMaps = yzCardMapper.selectCardDetail(iccid);
            dataList.add(cardInfoMaps);
        }
        System.err.println(dataList);
        return new ResponseJson().initSuccessOpen(dataList);
    }

    @Override
    public Map<String, Object> queryCardPackage(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dataList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String, Object> cardInfoMaps = yzCardMapper.queryCardPackage(iccid);
            dataList.add(cardInfoMaps);
        }
        System.err.println(dataList);
        return new ResponseJson().initSuccessOpen(dataList);
    }

    @Override
    public String mulCardStop(HttpServletRequest request) {
        //返回变量
        String apnCardStatusResult = "";
        //获取请求参数
        String map = (String) request.getAttribute("map");
        //fastJson工具转换
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> params = (Map<String, Object>) paramMap.get("Param");
        //拿到业务请求参数后转换为string数组
        List<String> msisdnList = JSONArray.parseArray(params.get("msisdn").toString(), String.class);
        for (String msisdn : msisdnList) {
            //根据msisdn从数据库中拿到调用api所需参数
            Map<String, Object> apiParams = yzCardMapper.selectApiParams(msisdn);
            //防止不存在的msisdn异常
            if (apiParams != null) {
                //判断区分运营商类别(目前考虑移动和电信5G、电信4G) 调用三方API
                String cdCode = (String) apiParams.get("cd_code");
                if ("YiDong_EC".equals(cdCode)) {
                    //移动
                    //停机参数
                    String operType = "0";
                    Query_YD queryYd = new Query_YD(apiParams, cdCode);
                    apnCardStatusResult = queryYd.FunctionApnCardStop(msisdn, operType);
                } else if ("DianXin_CMP_5G".equals(cdCode)) {
                    //电信5G
                    //停机参数
                    String orderTypeId = "19";
                    Query_DX5G queryDx5G = new Query_DX5G(apiParams);
                    apnCardStatusResult = queryDx5G.FunctionApnCardStop(msisdn, orderTypeId);
                } else if ("DianXin_CMP".equals(cdCode)) {
                    //电信4G
                    //停机参数
                    String orderTypeId = "19";
                    //固定值 保持为空
                    String acctCd = "";
                    Query_DX queryDx = new Query_DX(apiParams);
                    apnCardStatusResult = queryDx.FunctionApnCardStop(msisdn, orderTypeId, acctCd);

                }
            }
        }
        return apnCardStatusResult;
    }

    @Override
    public String mulCardStart(HttpServletRequest request) {
        //返回变量
        String apnCardStatusResult = "";
        //获取请求参数
        String map = (String) request.getAttribute("map");
        //fastJson工具转换
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> params = (Map<String, Object>) paramMap.get("Param");
        //拿到业务请求参数后转换为string数组
        List<String> msisdnList = JSONArray.parseArray(params.get("msisdn").toString(), String.class);
        for (String msisdn : msisdnList) {
            //根据msisdn从数据库中拿到调用api所需参数
            Map<String, Object> apiParams = yzCardMapper.selectApiParams(msisdn);
            //防止不存在的msisdn异常
            if (apiParams != null) {
                //判断区分运营商类别(目前考虑移动和电信5G、电信4G) 调用三方API
                String cdCode = (String) apiParams.get("cd_code");
                if ("YiDong_EC".equals(cdCode)) {
                    //移动
                    //复机参数
                    String operType = "1";
                    Query_YD queryYd = new Query_YD(apiParams, cdCode);
                    apnCardStatusResult = queryYd.FunctionApnCardStop(msisdn, operType);
                } else if ("DianXin_CMP_5G".equals(cdCode)) {
                    //电信5G
                    //复机参数
                    String orderTypeId = "20";
                    Query_DX5G queryDx5G = new Query_DX5G(apiParams);
                    apnCardStatusResult = queryDx5G.FunctionApnCardStop(msisdn, orderTypeId);
                } else if ("DianXin_CMP".equals(cdCode)) {
                    //电信4G
                    //复机参数
                    String orderTypeId = "20";
                    //固定值 保持为空
                    String acctCd = "";
                    Query_DX queryDx = new Query_DX(apiParams);
                    apnCardStatusResult = queryDx.FunctionApnCardStop(msisdn, orderTypeId, acctCd);

                }
            }
        }
        return apnCardStatusResult;
    }

    @Override
    //添加事务 回滚异常操作
    @Transactional
    public ResponseJson mulCardRenewal(HttpServletRequest request) {
        Map<String,Object> rMap = new HashMap<>();
        String map = (String) request.getAttribute("map");
        Map<String, Object> ParamMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) ParamMap.get("Param");
        Map<String, Object> verify = (Map<String, Object>) ParamMap.get("verify");
        //查询当前API登录用户agent_id
        Object appId = verify.get("appId");
        String agentId = agentPackageMapper.findAgentId(appId);
        //拿到iccid数组 资费组和资费计划
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);

        String packageId = null;
        String packetId = null;
        String validateType = null;
        try {
            packageId = param.get("packageId").toString();
            packetId = param.get("packetId").toString();
            validateType = param.get("validateType").toString();
        } catch (Exception e) {
            return new ResponseJson().initErrorOpen("500", "批量续费申请参数不能为空,请检查后重试！");
        }
        if (iccidList.size() > 500) {
            return new ResponseJson().initErrorOpen("500", "批量续费不得超过500张!");
        }
        //生成订单表信息 yz_order
        ResponseJson responseJson = this.generateTableInfo(iccidList, packageId, packetId, validateType, agentId);
        if (responseJson.get("status").equals("500")) {
            String errorMsg = (String) responseJson.get("message");
            return new ResponseJson().errorOpen("500", errorMsg);
        }
        Map<String, Object> cardPacket = null;
        //资费组和资费计划不能为空
        if (packageId != null && packageId.length() > 0 && packetId != null && packetId.length() > 0) {
            //生成主表信息
            //先查询续费资费计划 拿到资费计划单价
            cardPacket = yzCardPacketMapper.getPacketInfo(packetId);
            HashMap<Object, Object> hashMap = new HashMap<>();
            //校验是否有订单信息
            if (cardPacket == null) {
                return new ResponseJson().initErrorOpen("500", "该资费计划并没有订购信息，请检查后重试！");
            }
            hashMap.put("dept_id", agentId);
            hashMap.put("user_id", "1");
            hashMap.put("create_time", VeDate.getStringDate());
            hashMap.put("status", 0);
            hashMap.put("info", null);
            hashMap.put("is_send", 1);
            hashMap.put("card_sumCount", iccidList.size());
            hashMap.put("amount", Arith.mul(iccidList.size(), (Double) cardPacket.get("packet_price")));
            //生成主表信息
            renewalPrimaryMapper.insertPrimaryInfo(hashMap);
            //1.生成续费申请--资费计划表
            //参数准备 pid packet_info card_count
            Map<String, Object> findPacketMap = new HashMap<>();
            findPacketMap.put("dept_id", agentId);
            findPacketMap.put("packet_id", packetId);
            Map<String, Object> onePacket = yzCardPacketMapper.findOnePacket(findPacketMap);
            Map<String, Object> packetObj = new HashMap<>();
            packetObj.put("packet_info", JSON.toJSONString(onePacket));
            packetObj.put("card_count", iccidList.size());
            //插入主表id
            packetObj.put("p_id", hashMap.get("id"));
            packetObj.put("dept_id", agentId);
            packetObj.put("packet_wx_name", onePacket.get("packet_wx_name"));
            packetObj.put("packet_price", onePacket.get("packet_price"));
            packetObj.put("packet_flow", onePacket.get("packet_flow"));
            packetObj.put("packet_cost", onePacket.get("packet_cost"));
            packetObj.put("packet_valid_time", onePacket.get("packet_valid_time"));
            packetObj.put("packet_valid_name", onePacket.get("packet_valid_name"));
            packetObj.put("packet_id", onePacket.get("packet_id"));
            yzApplicationforRenewalMapper.insertRenewal(packetObj);
            for (String iccid : iccidList) {
                //2.生成续费--订单表
                //参数 订单号 主表id为p_id
                //查询订单号
                String orderNo = yzOrderMapper.selectOrderNo(iccid);
                HashMap<String, Object> orderMap = new HashMap<>();
                orderMap.put("ord_no", orderNo);
                orderMap.put("p_id", hashMap.get("id"));
                yzApplicationforRenewalPrimaryOrdNoMapper.insertOrderNo(orderMap);
                //3.生成续费--卡号表
                //参数 iccid 主表id为b_id b_id为yz_applicationfor_renewal的id
                yzApplicationforRenewalPrimaryIccidMapper.insertIccid(iccid, packetObj.get("id").toString());
            }
        } else {
            return new ResponseJson().initErrorOpen("500", "资费计划不能为空！");
        }
        rMap.put("packetName",cardPacket.get("packetName"));
        rMap.put("renewalStatus","审核中");
        rMap.put("iccidList",iccidList);
        return new ResponseJson().initSuccessOpen(rMap);
    }



    private ResponseJson generateTableInfo(List<String> iccidList, String packageId, String packetId, String validateType, String agentId) {
        for (String iccid : iccidList) {
            //卡必要信息
            Map<String, Object> cardInfo = yzCardMapper.getOneCardInfo(iccid);
            if (cardInfo == null) {
                return new ResponseJson().initErrorOpen("500", "卡号"+ iccid +"不存在,请检查信息！");
            }else {
                //资费计划信息
                Map<String, Object> packetInfo = yzCardPacketMapper.getOnePacketInfo(packageId, packetId);
                //生成订单
                this.insertOrderInfo(cardInfo, packetInfo, validateType);
            }
        }
        return new ResponseJson().successNewOpen(null);
    }

    private void insertOrderInfo(Map<String, Object> cardInfo, Map<String, Object> packetInfo, String validateType) {
        HashMap<String, Object> insertMap = new HashMap<>();
        String ord_no = com.yunze.common.utils.yunze.VeDate.getNo(8);
        insertMap.put("ord_no", ord_no);
        insertMap.put("ord_type", "2");
        insertMap.put("ord_name", "平台-批量充值");
        String iccid = cardInfo.get("iccid").toString();
        insertMap.put("iccid", iccid);
        insertMap.put("wx_ord_no", null);
        insertMap.put("status", "1");
        String price = packetInfo.get("packet_price").toString();
        insertMap.put("price", price);
        String packet_id = packetInfo.get("packet_id").toString();
        insertMap.put("packet_id", packet_id);
        insertMap.put("pay_type", "s");
        insertMap.put("cre_type", "sys");
        insertMap.put("is_profit", "0");
        insertMap.put("add_package", "0");
        insertMap.put("show_status", "0");
        insertMap.put("open_id", null);
        insertMap.put("agent_id", cardInfo.get("agent_id"));
        insertMap.put("profit_type", "0");
        insertMap.put("info", "API续费");
        insertMap.put("validate_type", validateType);
        insertMap.put("add_parameter", null);
        insertMap.put("is_audit", "0");
        insertMap.put("is_audi", "0");
        yzOrderMapper.insertOrder(insertMap);
    }

    /**
     * 查询修改后的数据--欣桥
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> queryDueExpireDateXQ(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dueExpireDateList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String,Object>  dueExpireDateXQ = yzCardMapper.queryDueExpireDateXQ(iccid);
            dueExpireDateList.add(dueExpireDateXQ);
        }
        return new ResponseJson().initSuccessOpen(dueExpireDateList);
    }
}
